<script setup lang="ts">
import { ref } from 'vue'
import { notification } from 'ant-design-vue'
import { cloneDeep } from 'lodash'
import type { Dayjs } from 'dayjs'
import dayjs from 'dayjs'
import ProductForm from '@/pages/product/components/product-form.vue'
import CustomerForm from '@/pages/customer/components/customer-form.vue'
import type { PurchaseDetailItemModel } from '@/api/purchase/purchase-list.ts'
import { addPurchaseDetailItem, updatePurchaseDetailItem } from '@/api/purchase/purchase-list.ts'

const emit = defineEmits(['purchaseDetailItemSave', 'cancel', 'ok'])

const value1 = ref<Dayjs>()

const isUpdate = ref(false)

const visible = ref(false)
const title = computed(() => {
  return isUpdate.value ? '编辑采购明细' : '新增采购明细'
})
function purchaseDetailItemSave(){
  console.log(`保存成功，返回刷新触发逻辑`)
}

// 采购明细对象
const formState = ref<PurchaseDetailItemModel>({
  itemId: 0, // 采购明细ID
  quantity: 0, // 斤数
  price: 0, // 单价
  purchaseId: 0, // 采购单号
  totalPrice: 0,
  actualAmount: 0,
  itemDate: undefined,
  itemType: 1,
  settlementStatus: 1,
  settlementAmount: 0,
  irSettlementAmount: 0,
  customerId: 0,
  productId: 0,
})

const productForm = ref<InstanceType<typeof ProductForm>>()

// 获取产品选中id
function productSelected(productId: number) {
  console.log(`当前选中的产品ID是：${productId}`)
  formState.value.productId = productId
}

const customerForm = ref<InstanceType<typeof CustomerForm>>()
function customerSelected(customerId: number) {
  console.log(`当前选中的客户ID是：${customerId}`)
  formState.value.customerId = customerId
}

// 打开对话框
function open(record?: PurchaseDetailItemModel) {
  console.log('打开采购明细操作弹框，关联编号：', record?.purchaseId)
  // 设定弹框显示添加项
  visible.value = true
  isUpdate.value = !!record?.value?.itemId

  formState.value = cloneDeep(record?.value)?? {
    purchaseId: record?.purchaseId, // 采购单号
    productId: undefined,
  }
}

// 确定 处理编辑或添加
async function handleOk() {
  try {
    // 如果是编辑，则进入编辑调用接口
    if (isUpdate.value) {
      const res = await updatePurchaseDetailItem(formState.value)
      if (res.code === 200) {
        notification.success({
          message: '修改完成',
          duration: 3,
        })
        visible.value = false
      }
      else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
      visible.value = false
    }
    else {
      if (formState.value.itemDate === ""|| formState.value.itemDate==undefined){
        console.log(`当前选择的日期是2：${ value1.value }`)
        formState.value.itemDate = dayjs(value1.value).format('YYYY-MM-DD')
      }
      console.log('添加采购明细', formState.value)
      const res = await addPurchaseDetailItem(formState.value)
      if (res.code === 200) {
        notification.success({
          message: '添加成功',
          duration: 3,
        })
        // 触发父级组件刷新采购明细
        purchaseDetailItemSave()
        visible.value = false
      } else {
        notification.error({
          message: res.msg,
          duration: 3,
        })
      }
    }
  } catch (e) {
    console.log(e)
  }
}

// 关闭对话框后操作
function cancelModal() {
  console.log('cancel')
}

// 日期格式化
function onPDChange(value, dateString) {
  if (dateString != '') {
    console.log(value, '   ', dateString)
    formState.value.itemDate = dayjs(dateString).format('YYYY-MM-DD')
  }
}

// 计算采购自动总价
function onTotalPriceChange() {
  // 采购数量*采购单价=采购自动总价
  if (formState.value.quantity > 0 || formState.value.price >0) {
    // 设定采购自动总价
    formState.value.totalPrice = formState.value.price*formState.value.quantity
    // 设定实际总价，去除个位的值，设定为0
    formState.value.actualAmount = setUnitsToZeroAndRemoveDecimal(formState.value.totalPrice)
  }
}
function setUnitsToZeroAndRemoveDecimal(num: number): number {
  // 获取整数部分
  const integerPart = Math.floor(num);
  // 将整数部分的个位数设置为 0
  const result = Math.floor(integerPart / 10) * 10;
  // 返回结果
  return result;
}

// 计算剩余结算金额
function onIrSettlementAmountChange() {
  console.log('已结算金额:', formState.value.settlementAmount)
  if (formState.value.actualAmount > 0 || formState.value.settlementAmount>=0){
    formState.value.irSettlementAmount = formState.value.actualAmount-formState.value.settlementAmount
    // 设定结算状态
    // settlementStatus 结算状态，1已结算，2未结算，3部分结算
    if (formState.value.settlementAmount === 0) {
      console.log('未结算:', formState.value.settlementAmount)
      // 未结算
      formState.value.settlementStatus = 2
    }
    else if (formState.value.settlementAmount > 0 && formState.value.irSettlementAmount > 0){
      formState.value.settlementStatus = 3
    }
    else {
      formState.value.settlementStatus = 1
    }
  }
}

defineExpose({
  open,
})
</script>

<template>
  <a-modal v-model:open="visible" width="800px" :title="title" @ok="handleOk" @cancel="cancelModal">
    <a-form :model="formState" name="basic" autocomplete="off">
      <a-form-item label="采购产品" name="productId" :rules="[{ required: true, message: '选择本次采购产品' }]">
        <ProductForm ref="productForm" v-model:value="formState.productId" @productSelected="productSelected"/>
      </a-form-item>
      <a-form-item label="采购日期" name="value1" :rules="[{ required: false, message: '请选择开始时间' }]">
        <a-date-picker v-model:value="value1" style="width: 100%" format="YYYY-MM-DD"  @change="onPDChange"/>
      </a-form-item>
      <a-form-item label="采购类型" name="itemType" :rules="[{ required: true, message: '请选择采购类型' }]">
        <a-select v-model:value="formState.itemType" placeholder="请选择采购类型">
          <a-select-option value="1">
            正常采购
          </a-select-option>
          <a-select-option value="2">
            全额抵消
          </a-select-option>
          <a-select-option value="3">
            部分抵消
          </a-select-option>
        </a-select>
      </a-form-item>
      <a-form-item label="采购数量(斤数)" name="quantity" :rules="[{ required: true, message: '请输入采购数量' }]">
        <a-input-number v-model:value="formState.quantity" :min="0" :step="0.01" string-mode @change="onTotalPriceChange"/>
      </a-form-item>
      <a-form-item label="采购单价" name="price" :rules="[{ required: true, message: '请输入采购单价' }]">
        <a-input-number v-model:value="formState.price" :min="0" :step="0.01" string-mode  @change="onTotalPriceChange"/>
      </a-form-item>
      <a-form-item label="采购自动总价" name="totalPrice" :rules="[{ required: true, message: '自动计算采购总价' }]">
        <a-input-number v-model:value="formState.totalPrice" :min="0" :step="0.01" string-mode readonly/>
      </a-form-item>
      <a-form-item label="采购实际总价" name="actualAmount" :rules="[{ required: true, message: '请输入实际总价' }]">
        <a-input-number v-model:value="formState.actualAmount" :min="0" :step="0.01" string-mode @change="onIrSettlementAmountChange"/>
      </a-form-item>
      <a-form-item label="采购客户" name="customerId" :rules="[{ required: true, message: '请选择采购所属客户' }]">
        <CustomerForm ref="customerForm" v-model:value="formState.customerId" @customerSelected="customerSelected"/>
      </a-form-item>
      <a-form-item label="已结算金额" name="settlementAmount" :rules="[{ required: true, message: '请输入已结算金额' }]">
        <a-input-number v-model:value="formState.settlementAmount" :min="0" :step="0.01" string-mode @change="onIrSettlementAmountChange"/>
      </a-form-item>
      <a-form-item label="剩余结算金额" name="irSettlementAmount" :rules="[{ required: true, message: '自动计算剩余结算金额' }]">
        <a-input-number v-model:value="formState.irSettlementAmount" :min="0" :step="0.01" string-mode readonly/>
      </a-form-item>
      <a-form-item label="结算状态" name="settlementStatus" :rules="[{ required: true, message: '请选择结算状态' }]">
        <a-select v-model:value="formState.settlementStatus" placeholder="请选择结算状态" readonly>
          <a-select-option value="1">
            已结算
          </a-select-option>
          <a-select-option value="2">
            未结算
          </a-select-option>
          <a-select-option value="3">
            部分结算
          </a-select-option>
        </a-select>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<style scoped lang="less">

</style>